import string
import random
from urllib.parse import urljoin

import requests as req
from fake_useragent import UserAgent
from tqdm import tqdm

from utils import create_folder_if_not_exist

base_domain = "https://www.riolis.ru/"


def download_image(image_link: str, filename: str = None) -> str:
    """Download image from link. Link is relative to base_domain. """
    def generate_random_string(length: int) -> str:
        """Generate random string of given length."""
        return "".join(random.choice(string.ascii_letters) for i in range(length))
    r = req.get(urljoin(base_domain, image_link), headers={"User-Agent": UserAgent().random})
    filename = filename or "images/" + generate_random_string(15) + ".jpg"
    with open(filename, "wb") as f:
        f.write(r.content)
    return filename


def get_product_id(url: str) -> str:
    """Get product id from url.
    Example: https://www.riolis.ru/catalog/details_12345.html -> 12345"""
    return url.split("_")[-1].split(".")[0]


def get_products_id(filename: str):
    """
    :param filename: file with ids. Each line is link to product
    :return:
    """
    with open(filename, "r") as f:
        return [get_product_id(line) for line in f.readlines()[:-1]]


def get_product_photo_links_available(product_id: str) -> list:
    """Example 1234 -> [https://www.riolis.ru/zoom/photos/1234.jpg, https://www.riolis.ru/zoom/photos/1234_2.jpg,
    https://www.riolis.ru/zoom/photos/1234_3.jpg .....] """
    i = 0
    while True:
        i += 1
        if i == 1:
            yield f"https://www.riolis.ru/zoom/photos/{product_id}.jpg"
        else:
            yield f"https://www.riolis.ru/zoom/photos/{product_id}_{i}.jpg"


if __name__ == "__main__":
    create_folder_if_not_exist("high_res1")
    ids = get_products_id("goods_ids.txt")
    for id in tqdm(ids, total=len(ids)):
        for i, link in enumerate(get_product_photo_links_available(id)):
            if req.get(link).status_code == 404:
                break
            download_image(link, filename=f"high_res1/{id}_{i}.jpg")
